import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {tableConfig, header} from '../data/config'
import store from 'store'
// import {getUrlParam} from '../data/util'

const base = url.base,
  getHouseBuildingList = request.getHouseBuildingList,
  uploadHouseResource = request.uploadHouseResource;

let table
let storeData

table = $('#table').bootstrapTable($.extend({}, tableConfig, {
  url: base + '/admin/houseStatistics/facade.json',
  queryParams: function (params) {
    console.log("params:", params)
    return $.extend({
      currentPage: params.pageNumber,
      pageSize: params.pageSize
    }, $('#searchForm').serializeObject())
  }, ajax: function (params) {  //  自定义ajax
    $.ajax({
      url: params.url,
      type: params.type,
      contentType: params.contentType,
      headers: {
        myToken: Cookies.get('myToken')
      },
      data: params.data
    })
      .done(function (res) {
        let arr = res.object instanceof Array ? res.object : res.object.elements
        // let arr2 = arr.reverse()
        setSearch(arr)
        params.success({
          total: res.object.totalRows,
          rows: arr
        })
      })
  },
  columns: [
    {
      field: 'buildName',
      title: '楼盘名称',
      valign: 'middle'
    }, {
      field: 'hsTypeNum',
      title: '户型数',
      valign: 'middle'
    }, {
      field: 'hsBuildUnitNum',
      title: '楼栋数',
      valign: 'middle'
    }, {
      field: 'hsBuildNum',
      title: '总计房源数量',
      valign: 'middle'
    }, {
      field: 'hsOnBuildNum',
      title: '开盘房源数量',
      valign: 'middle'
    }, {
      field: 'hsSoldNum',
      title: '已售房源数',
      valign: 'middle'
    }, {
      field: 'hsOnBuildNum',
      title: '剩余房源数',
      valign: 'middle',
      formatter: (index, row) => {
        return row.hsOnBuildNum - row.hsSoldNum
      }
    }, {
      field: 'status',
      valign: 'middle',
      align: 'center',
      width: '240px',
      title: '操作',
      formatter: (index, row, a) => {
        return `<div class="btn-group">
                  <button type="button" data-id="${ row.buildIdStr }" class="btn btn-management">房源管理</button>                  
                   <button type="button" data-id="${ row.buildIdStr }" class="btn btn-default">户型管理</button>                  
                </div>`
      }
    }
  ]
}))

// 点击列表的时候传递数据到全局变量
table.on('click-row.bs.table', (e, data, el) => {
  storeData = data
})

// 初始化模态框楼盘列表数据
getBuildList();

// 初始化导入验证
leadIn()

// 获取楼盘列表
function getBuildList() {

  $.ajax({
    headers: header,
    type: 'GET',
    url: base + getHouseBuildingList
  })
    .done(function (res) {
      console.log("获取楼盘成功")

      let dom = $('#developerId'),
        html = '<option value="">请选择</option>',
        i = 0,
        data = res,
        len = data.length;

      for (; i < len; i++) {
        html += `<option value="${ data[i].id }">${ data[i].propertyName }</option>`
      }

      dom.html(html);
      dom.selectize();

    })
    .fail(function (err) {
      console.log(err)
    })
}

// 批量导入模态框
function leadIn() {

  const isIe = navigator.appVersion.indexOf("MSIE") !== -1

  const allowType = ['xls', 'xlsx']

  let $el = $('#batch-import-modal-file'),
    $err = $('#batch-import-modal-error'),
    $submit = $('#batch-import-modal-submit');

  $el.on('change', changeHandler)

  function changeHandler($e) {
    const v = $e.target.value
    const f = $e.target.files[0]
    const size = (f.size / 1024).toFixed(1)
    const type = v.substr(v.lastIndexOf('.') + 1)

    console.log(f)
    if (allowType.indexOf(type) === -1) {

      $err.text('文件格式不支持,格式只能是:' + allowType.join(',')).show()
      $submit.attr('disabled', true)

      $el[0].value = ''

      return false
    }

    $err.text('').hide()
    $submit.attr('disabled', false)

    console.log('size:' + size)
    console.log('ext:' + type)
  }

  $submit.unbind('click');

  $submit.on('click', (e) => {
    e.preventDefault;

    let formData = new FormData($('#uploadForm')[0]),
      developerId = $('#developerId').val(),
      developerName = $('#developerId option:selected').text();

    let loading_modal = layer.msg('正在导入...', {
      icon: 16,
      time: 0,
      shade: .5
    })

    formData.append('developerId', developerId + ',' + developerName)

    $submit.attr('disabled', true);

    $.ajax({
      headers: header,
      type: 'POST',
      cache: false,
      url: base + uploadHouseResource,
      processData: false,
      contentType: false,
      dataType: "json",
      data: formData
    })
      .done(function (res) {
        if (res.code === 0) {
          layer.msg(`导入成功`, {
            icon: 6
          })
          setTimeout(() => {
            window.location.reload()
          }, 6000)
        } else {
          layer.msg(res.message, {
            icon: 10
          })
          setTimeout(() => {
            window.location.reload()
          }, 10000)
        }

      })
      .fail(function (err) {
        layer.msg(`导入失败`, {
          icon: 5
        })
        console.log(err)
      })
      .complete(function () {

        // $submit.attr('disabled', false);
        // layer.close(loading_modal);
        // $('#batch-import-modal').modal('hide');
        // window.location.reload()
      })
  })

}

$(document).on('click', '#table .btn-management', (e) => {
  e.preventDefault()

  console.log(e.target)
  store.set('storeData', storeData)

  let house = $(e.target).attr('data-id')
  window.location.href = `./house.html?house=${house}`
  // window.location.href = `./test.html?id=${house}`
});

$(document).on('click', '#table .btn-default', (e) => {
  e.preventDefault()

  console.log(e.target)
  store.set('storeData', storeData)

  let type = $(e.target).attr('data-id')
  window.location.href = `./type.html?house=${type}`
});

$('#searchForm #search-btn').on('click', () => {
  console.log($('#searchForm').serializeObject())
  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage: 1,
    }, {buildIdSearch: $('#devId').val()})
  })

})

function setSearch(res) {
  if ($('#devId').children().length < 2) {
    res.forEach(row => {
      let str = `<option value="${row.buildId}">${row.buildName}</option>`
      $('#devId').append(str)
    })
  }
}
